<template>
  <div>
    <div>
      <el-form :inline="true">
        <el-form-item>
          <el-button type="primary" @click="handleAdd()" >调拨申请</el-button>
        </el-form-item>
      </el-form>
    </div>
    <custom-table
      :columns="columns"
      :data="allotApplyList"
      :tableLoadingFlag="tableLoadingFlag"
      :operationColumn="operationColumn"
      :pagination="pagination">
    </custom-table>
    <el-dialog title="调拨申请" center :visible.sync="allotApplyFormVisible" :close-on-click-modal="false">
      <el-form class="form-horizontal" :model="applyDto" :rules="applyRules" label-width="120px"
               ref="applyForm">
        <el-form-item label="申请人" prop="name">
          <el-input v-model.trim="applyDto.name" auto-complete="off" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="调出方">
          <el-row>
            <el-col :span="6">
              <el-select v-model="applyDto.calloutProvince" clearable placeholder="调出省份" @change="getAllCity(1)" >
                <el-option
                  v-for="item in allProvince"
                  :key="item.provinceCode"
                  :label="item.province"
                  :value="item.provinceCode">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select v-model="applyDto.calloutCity" clearable placeholder="请选择城市" @change="getAllPointSource(1)">
                <el-option
                  v-for="item in calloutAllCity"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="12">
              <el-select v-model="applyDto.calloutPointId" clearable placeholder="请选择调出方" @change="onCallOut">
                <el-option
                  v-for="item in calloutAllCitySource"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="接收方">
          <el-row>
            <el-col :span="6">
              <el-select v-model="applyDto.provinceCode" clearable placeholder="接收省份" @change="getAllCity(2)" >
                <el-option
                  v-for="item in allProvince"
                  :key="item.provinceCode"
                  :label="item.province"
                  :value="item.provinceCode">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select v-model="applyDto.receiveCity" clearable placeholder="请选择城市" @change="getAllPointSource(2)">
                <el-option
                  v-for="item in receiveAllCity"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-col>
          <el-col :span="12">
            <el-select v-model="applyDto.receivePointId" clearable placeholder="请选择接收方" @change="onGetReceiver">
              <el-option
                v-for="item in receiveAllCitySource"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="接收人" prop="receiverName">
          <el-input v-model.trim="applyDto.receiverName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="接收人联系方式" prop="receiverTel">
          <el-input v-model.trim="applyDto.receiverTel" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="接收人详细地址" prop="receiverAddress">
          <el-input v-model.trim="applyDto.receiverAddress" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="要求发出时间" prop="requiredDate">
          <el-date-picker
            v-model="applyDto.requiredDate"
            type="date"
            placeholder="选择日期"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            :picker-options="requirePicker">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="型号" prop="modelId">
          <el-select v-model.number="applyDto.modelId" placeholder="请选择型号" @change="onItemName">
            <el-option
              v-for="item in modelOptions"
              :key="item.id"
              :label="item.code"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品名称" prop="itemName">
          <el-input v-model.trim="applyDto.itemName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-select v-model.number="applyDto.unit" placeholder="请选择单位">
            <el-option key="1" label="台" value="台"></el-option>
            <el-option key="2" label="套" value="套"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="num">
          <el-input-number v-model.number="applyDto.num" :min="1" :step="1"></el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="applyDto.remark" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onBtnSubmit()" style="float: right;" v-no-more-click>确定</el-button>
          <el-button @click="onBtnCancel()" style="float: right;margin-right: 10px;">
            取消
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="申请详情" center :visible.sync="applyDetailVisible" wdith="100%" :close-on-click-modal="false">
      <el-steps align-center :active="applyStep" finish-status="success" :process-status="processStatus">
        <el-step title="调拨申请">
        </el-step>
        <el-step title="审核"></el-step>
        <el-step title="审批"></el-step>
        <el-step title="发放"></el-step>
      </el-steps>
      <div v-if="applyStep>=1">
        <h4>审核结果：</h4>
        <custom-table
          :columns="columnDailogAudit"
          :data="applyAuditDetail"
          :tableLoadingFlag="tableLoadingFlag">
        </custom-table>
      </div>
      <div v-if="applyStep>=2">
        <h4>审批结果：</h4>
        <custom-table
          :columns="columnDailogApprove"
          :data="applyApproveDetail"
          :tableLoadingFlag="tableLoadingFlag">
        </custom-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { apiApply, apiGetItem, apiAllotSelfList, apiAllotSelfDetail } from '@/api/allot/apply'
  import { apiGetCity, apiGetModelList, apiGetAllProvinceSource, apiGetAllPointSource } from '@/api/dictionary'
  import { apiGetAllReceiver } from '@/api/basic/info/inside/office'
  import { getUserId, getName, getRoleType } from '@/utils/token'
  import CustomTable from '@/components/table/CustomTable'
  import { parseTime } from '@/utils'

  export default {
    components: {
      CustomTable
    },
    created () {
      this.flag = false
      this.def()
      this.getAllProvince()
      this.getSelfApplyList()
    },
    data () {
      return {
        // 表单列
        columnDailogAudit: [
          {label: '审核人', name: 'name', width: '100', align: 'center'},
          {label: '审核时间', name: 'time', width: '180', align: 'center',formatter: this.formatTime},
          {label: '审核结果', name: 'result', width: '150', align: 'center', formatter: this.formatStatus},
          {label: '原因', name: 'reason', align: 'center'}
        ],
        columnDailogApprove: [
          {label: '审批人', name: 'name', width: '100', align: 'center'},
          {label: '审批时间', name: 'time', width: '180', align: 'center',formatter: this.formatTime},
          {label: '审批结果', name: 'result', width: '150', align: 'center', formatter: this.formatStatus},
          {label: '原因', name: 'reason', align: 'center'}
        ],
        columns: [
          {label: 'ID', name: 'id', width: '80', align: 'center'},
          {label: '工单号', name: 'applicationNo', width: '150', align: 'center'},
          {label: '申请日期', name: 'applicationDate', width: '200', align: 'center', formatter: this.formatTime},
          {label: '申请状态', name: 'applicationStatus', width: '150', align: 'center'},
          {label: '申请型号', name: 'model', width: '150', align: 'center'},
          {label: '申请产品', name: 'itemName', width: '150', align: 'center'},
          {label: '数量', name: 'num', width: '150', align: 'center'},
          {label: '申请人', name: 'proposerName', width: '150', align: 'center'},
          {label: '接收人地址', name: 'receiverAddress', width: '150', align: 'center'},
          {label: '接收人姓名', name: 'receiverName', width: '150', align: 'center'},
          {label: '接收人联系电话', name: 'receiverTel', width: '250', align: 'center'},
          {label: '备注', name: 'remark', width: '150', align: 'center'},
          {label: '审批人', name: 'approverName', width: '150', align: 'center'}
        ],
        // 表单操作栏
        operationColumn: {
          width: '80',
          operations: [
            {name: '详情', callback: this.getDetailSelfApply}
          ]
        },
        processStatus: 'wait',
        tableLoadingFlag: false,
        applyStep: 0,
        applyAuditDetail: [
          {
            name: '',
            time: '',
            result: '',
            reason: ''
          }
        ],
        applyApproveDetail: [
          {
            name: '',
            time: '',
            result: '',
            reason: ''
          }
        ],
        roleType: getRoleType(),
        allotApplyList: [],
        // 备机申请模态框默认隐藏
        allotApplyFormVisible: false,
        // 申请步骤条默认隐藏
        applyDetailVisible: false,
        requirePicker: {
          disabledDate (time) {
            return time.getTime() < Date.now() - 8.64e7
          }
        },
        pagination: this.getData(this.getSelfApplyList),
        provinceCode: '',
        applyDto: {
          proposerId: '',
          proposerName: '',
          receiverName: '',
          calloutProvince: '',
          calloutCity: '',
          calloutPointId: '',
          calloutPointType: '',
          receiveProvince: '',
          receiveCity: '',
          receivePointId: '',
          receivePointType: '',
          receiverId: '',
          receiverTel: '',
          receiverAddress: '',
          // 调出方地址
          calloutAddress: '',
          address: '',
          itemName: '',
          modelId: '',
          num: '',
          unit: '',
          provinceOut: '',
          provinceIn: '',
          provinceCode: '',
          requiredDate: '',
          remark: '',
          name: ''
        },
        allProvince: [],
        calloutAllCity: [],
        calloutAllCitySource: [],
        receiveAllCity: [],
        receiveAllCitySource: [],
        listQuery: {
          province: '',
          city: ''
        },
        applyRules: {
          receiverAddress: [
            {required: true, message: '请填写接收人详细地址', trigger: 'blur'},
            {max: 255, message: '长度不得超过255字符', trigger: 'blur'}
          ],
          receiverTel: [
            {required: true, message: '请填写接收人联系方式', trigger: 'blur'}
          ],
          receiverName: [
            {required: true, message: '请填写接收人姓名', trigger: 'blur'},
            {max: 20, message: '长度不得超过20字符', trigger: 'blur'}
          ],
          itemName: [
            {required: true, message: '请填写产品名称', trigger: 'blur'},
            {max: 50, message: '长度不超过 50 个字符', trigger: 'blur'}
          ],
          modelId: [{type: 'number', required: true, message: '请填写型号', trigger: 'change'}],
          unit: [{required: true, message: '请选择单位', trigger: 'change'}],
          remark: [
            {max: 255, message: '长度不得超过255字符', trigger: 'blur'},
            {required: true, message: '请填写申请备注', trigger: 'blur'}
          ]
        },
        modelOptions: this.selectedModelInit()
      }
    },
    methods: {
      formatStatus (row, column, cellValue) {
        if (cellValue === 1) {
          return '不通过'
        }
        return '通过'
      },
      formatTime (row, column, cellValue) {
        return parseTime(cellValue)
      },
      // 获取个人备机申请一览
      getSelfApplyList (listquery) {
        apiAllotSelfList(listquery).then(response => {
          this.allotApplyList = response.data
          this.pagination.totalRecords = response.totalRecords
          this.tableLoadingFlag = false
        })
      },
      // 调拨申请框弹出
      handleAdd () {
        this.allotApplyFormVisible = true
      },
      // 获取拥有办事处,外包商的省份
      getAllProvince () {
        apiGetAllProvinceSource().then(response => {
          this.allProvince = response.data
        })
      },
      // 根据省市获取办事处,外包商一览
      getAllPointSource (type) {
        if (type == '1') {
          this.applyDto.calloutPointId = ''
          let listQuery = {
            province: this.applyDto.calloutProvince,
            city: this.applyDto.calloutCity
          }
          apiGetAllPointSource(listQuery).then(response => {
            this.calloutAllCitySource = response.data
          })
        } else {
          this.applyDto.receivePointId = ''
          this.applyDto.receiverName = ''
          this.applyDto.receiverTel = ''
          this.applyDto.receiverAddress = ''
          let listQuery = {
            province: this.applyDto.provinceCode,
            city: this.applyDto.receiveCity
          }
          apiGetAllPointSource(listQuery).then(response => {
            this.receiveAllCitySource = response.data
          })
        }
      },
      // 根据省code获取市一览
      getAllCity (type) {
        if (type == '1') {
          this.applyDto.calloutCity = ''
          this.applyDto.calloutPointId = ''
          this.calloutAllCity = ''
          if (this.applyDto.calloutProvince !== '') {
            let listQuery = {
              province: this.applyDto.calloutProvince
            }
            apiGetCity(listQuery).then(response => {
              this.calloutAllCity = response.data
            })
          }
        } else {
          this.applyDto.receiveCity = ''
          this.applyDto.receivePointId = ''
          this.receiveAllCity = ''
          this.applyDto.receiverName = ''
          this.applyDto.receiverTel = ''
          this.applyDto.receiverAddress = ''
          if (this.applyDto.provinceCode !== '') {
            let listQuery = {
              province: this.applyDto.provinceCode
            }
            apiGetCity(listQuery).then(response => {
              this.receiveAllCity = response.data
            })
          }
        }
      },
      getDetailSelfApply (row) {
        apiAllotSelfDetail(row.id).then(response => {
          if (response.data.applicationStatus === 1) {
            // 已提交申请，待审核
            this.applyStep = 0
            this.processStatus = 'success'
          } else if (response.data.applicationStatus === 5) {
            // 设备已全部发放
            this.applyStep = 3
            this.processStatus = 'success'
          } else if (response.data.applicationStatus === 2) {
            // 已通过审核，待审批
            this.applyStep = 1
            this.processStatus = 'success'
          } else if (response.data.applicationStatus === 3 || response.data.applicationStatus === 4) {
            // 已通过审批，待发放
            this.applyStep = 2
            this.processStatus = 'success'
          } else if (response.data.applicationStatus === 6 && (response.approve === undefined || response.approve === null)) {
            // 未通过审核
            this.applyStep = 1
            this.processStatus = 'error'
          } else if (response.data.applicationStatus === 6 && response.approve !== undefined && response.approve !== null) {
            // 未通过审批
            this.applyStep = 2
            this.processStatus = 'error'
          }
          if (this.applyStep >= 1) {
            this.applyAuditDetail[0].name = response.audit.name
            this.applyAuditDetail[0].time = response.audit.approveDate
            this.applyAuditDetail[0].result = response.audit.result
            this.applyAuditDetail[0].reason = response.audit.cause
          }
          if (this.applyStep >= 2) {
            this.applyApproveDetail[0].name = response.approve.name
            this.applyApproveDetail[0].time = response.approve.approveDate
            this.applyApproveDetail[0].result = response.approve.result
            this.applyApproveDetail[0].reason = response.approve.cause
          }
          this.applyDetailVisible = true
        })
      },
      def () {
        this.applyDto.name = getName()
      },
      onItemName (listQuery) {
        apiGetItem(listQuery).then(response => {
          this.applyDto.itemName = response.data
        })
      },
      onGetReceiver (val) {
        let obj = {}
        obj = this.receiveAllCitySource.find((item) => {
          return item.id === val
        })
        let receiveType = obj.type.substring(obj.type.length - 3)
        if (receiveType === '办事处') {
          this.applyDto.receivePointType = 0
        } else if (receiveType === '外包商') {
          this.applyDto.receivePointType = 1
        }
        receiveType = ''
        this.applyDto.receiverName = ''
        this.applyDto.receiverTel = ''
        this.applyDto.receiverAddress = ''
        this.applyDto.receiveProvince = this.applyDto.provinceCode
        if (this.applyDto.receivePointId > 0) {
          let receiveListQuery = {
            provinceCode: this.applyDto.receiveProvince,
            pointId: this.applyDto.receivePointId,
            receivePointType: this.applyDto.receivePointType
          }
          apiGetAllReceiver(receiveListQuery).then(response => {
            this.applyDto.receiverName = response.data[0].logisticsContact
            this.applyDto.receiverTel = response.data[0].logisticsTel
            this.applyDto.receiverAddress = response.data[0].logisticsAddr
          })
        }
      },
      onCallOut(val) {
        let obj1 = {}
        obj1 = this.calloutAllCitySource.find((item) => {
          return item.id === val
        })
        let calloutType = obj1.type.substring(obj1.type.length - 3)
        if (calloutType === '办事处') {
          this.applyDto.calloutPointType = 0
        } else if (calloutType === '外包商') {
          this.applyDto.calloutPointType = 1
        }
        calloutType = ''
        let calloutListQuery = {
          provinceCode: this.applyDto.calloutProvince,
          pointId: this.applyDto.calloutPointId,
          calloutPointType: this.applyDto.calloutPointType
        }
        apiGetAllReceiver(calloutListQuery).then(response => {
          this.applyDto.calloutAddress = response.data[0].logisticsAddr
        })
      },
      // 型号选择初始化
      selectedModelInit () {
        apiGetModelList().then(response => {
          let modelList = response.data
          let model = []
          let temp = {}
          for (let i in modelList) {
            if (!temp[modelList[i].code]) {
              temp[modelList[i].code] = modelList[i].id
            }
          }
          for (let k in temp) {
            model.push({'code': k, 'id': temp[k]})
          }
          this.modelOptions = model
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      onBtnSubmit () {
        this.$refs['applyForm'].validate((valid) => {
          if (this.applyDto.calloutProvince === '' || this.applyDto.calloutCity === '' ||
            this.applyDto.calloutPointId === '' || this.applyDto.receiveProvince === '' ||
            this.applyDto.receiveCity === '' || this.applyDto.receivePointId === '') {
            this.$message({
              showClose: true,
              message: '调出方或接收方不能为空',
              type: 'error'
            })
            return
          }
          if (this.applyDto.calloutAddress === this.applyDto.receiverAddress) {
            this.$message({
              showClose: true,
              message: '调出方和接收方不能相同',
              type: 'error'
            })
            return
          }
          if (valid) {
            // 调拨申请
            this.applyDto.proposerId = getUserId()
            this.applyDto.proposerName = getName()
//            dto.provinceCode = this.location.provinceCode
            apiApply(this.applyDto).then(() => {
              this.$refs['applyForm'].resetFields()
              this.getSelfApplyList()
              this.onBtnCancel()
              this.$message({
                showClose: true,
                message: '调拨申请成功',
                type: 'success'
              })
            })
            this.flag = true
          } else {
            return false
          }
        })
      },
      onBtnCancel () {
        this.$refs['applyForm'].resetFields()
        this.allotApplyFormVisible = false
      }
    }
  }
</script>
